package com.rf.richfitwheel.common.errors;

import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.Result;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Wen Shaokun
 * @Description
 * @Created 2022/02/16 - 14:14
 */
public class ResultCache {
    private static final Map<Object, R> resultCodeMap = new ConcurrentHashMap<>();

    private static final String ZEROPAD = "4";

    public static R get(Object object) {
        if (resultCodeMap.containsKey(object)) {
            return resultCodeMap.get(object);
        }
        try {
            // 传入的object都是enum类型
            Enum<?> codeEnum = (Enum<?>) object;
            // 获取@CodePrefix注解属性
            CodePrefix codePrefix = object.getClass().getAnnotation(CodePrefix.class);
            // 获取@C注解属性
            C c = object.getClass().getField(codeEnum.name()).getAnnotation(C.class);
            int codeVal = c != null ? c.value() : codeEnum.ordinal();
            // 拼接错误code, i.e. 40301
            String code = codePrefix != null ? String.format("%s%0" + ZEROPAD + "d", codePrefix.value(), codeVal)
                    : String.valueOf(codeVal);
            String msg = (c != null && !StringUtils.isEmpty(c.msg())) ? c.msg() : codeEnum.name();
            // 创建返回错误信息
            R r = R.error(code, msg);
            resultCodeMap.put(object, r);
            return r;
        } catch (Exception e) {
            throw new Error(e);
        }

    }
}
